package com.azarias.monitor;
import com.azarias.model.pojo.Registry;
import com.azarias.model.pojo.ServiceInstance;
import javafx.scene.web.WebHistory;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @description: 后台线程 用以清理失效service
 * @author: Azarias_Jx
 * @date: 2022/1/2 15:42
 */
@Slf4j
public class Daemon extends Thread{
    /**
     * 检查服务实例是否存活的间隔
     */
    private static final Long CHECK_ALIVE_INTERVAL = 60 * 1000L;

    private Registry registry = Registry.getInstance();

    @Override
    public void run() {
        Map<String, Map<String, ServiceInstance>> registryMap = null;
        while (true){
            try{
                registryMap = registry.getRegistry();
                for (String serviceName : registryMap.keySet()) {
                    Map<String, ServiceInstance> stringServiceInstanceMap = registryMap.get(serviceName);
                    for (ServiceInstance serviceInstance : stringServiceInstanceMap.values()) {
                        if(!serviceInstance.isAlive()){
                            registry.remove(serviceName,serviceInstance.getServiceInstanceId());
                        }
                    }
                }
                Thread.sleep(CHECK_ALIVE_INTERVAL);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
